package com.jiangyg.mall.rabbitmq;

import com.jiangyg.mall.core.utils.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * 类描述：RabbitMQ配置
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-01-12
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties({RabbitProperties.class})
public class RabbitAutoConfiguration implements InitializingBean {

    @Bean
    @Primary
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter());
        return rabbitTemplate;
    }

    /**
     * 功能描述：定义消息转换器
     * <p>使用此消息转换器可在监听中直接转自定义对象</p>
     *
     * @return 消息转换器
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Override
    public void afterPropertiesSet() {
        Logger.info(log, () -> "[项目启动]-初始化 RabbitMQ 配置……");
    }

}
